package com.zzy.netty.learn.client;

import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.jboss.netty.bootstrap.ClientBootstrap;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelFuture;
import org.jboss.netty.channel.ChannelPipeline;
import org.jboss.netty.channel.ChannelPipelineFactory;
import org.jboss.netty.channel.Channels;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.jboss.netty.handler.codec.string.StringDecoder;
import org.jboss.netty.handler.codec.string.StringEncoder;

import com.zzy.netty.learn.common.Request;
import com.zzy.netty.learn.common.util.SerializeUtil;
/**
 * netty客户端入门
 * @author -琴兽-
 *
 */
public class NettyClient {

	public static void main(String[] args) {
		
		//服务类
		ClientBootstrap bootstrap = new  ClientBootstrap();
		
		//线程池
		ExecutorService boss = Executors.newCachedThreadPool();
		ExecutorService worker = Executors.newCachedThreadPool();
		
		//socket工厂      //客户端工厂
		bootstrap.setFactory(new NioClientSocketChannelFactory(boss, worker));
		
		//管道工厂
		bootstrap.setPipelineFactory(new ChannelPipelineFactory() {
			
			@Override
			public ChannelPipeline getPipeline() throws Exception {
				ChannelPipeline pipeline = Channels.pipeline();
				pipeline.addLast("decoder", new StringDecoder());
				pipeline.addLast("encoder", new StringEncoder());
				pipeline.addLast("hiHandler", new NettyClientMsgHandler());  //消息处理类
				return pipeline;
			}
		});
		
		//连接服务端   //可以连多个会话
		ChannelFuture connect = bootstrap.connect(new InetSocketAddress("127.0.0.1", 10102));
		Channel channel = connect.getChannel();
		
		System.out.println("-------------client start-----------------");
		
		
		//发送消息
		String playerId=System.currentTimeMillis()+"";
		Request request=new Request("room1", playerId ,"大家好!".getBytes());
		channel.write(SerializeUtil.fastJsonSerialize(request));

	}

}
